//
//  GTDeleteCellView.m
//  news
//
//  Copyright © 2022 sinosun. All rights reserved.
//

#import "GTDeleteCellView.h"

@interface GTDeleteCellView()

@property (nonatomic, strong, readwrite) UIView *backgroundView;
@property (nonatomic, strong, readwrite) UIButton *deleteButton;
@property (nonatomic, copy, readwrite) dispatch_block_t deleteBlock;

@end

@implementation GTDeleteCellView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:({
            self.backgroundView = [[UIView alloc] initWithFrame:self.bounds];
            self.backgroundView.backgroundColor = [UIColor lightGrayColor];
            self.backgroundView.alpha = 0.5;
            
            // 给背景也添加一个手势
            UITapGestureRecognizer* gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_deleteButtonClicked)];
            [self.backgroundView addGestureRecognizer:gestureRecognizer];
            
            self.backgroundView;
        })];
        
        [self addSubview:({
            self.deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 50)];
            self.deleteButton.backgroundColor = [UIColor blueColor];
            [self.deleteButton addTarget:self action:@selector(_deleteButtonClicked) forControlEvents:(UIControlEventTouchDown)];
            self.deleteButton;
        })];
    }
    return self;
}

- (void)showDeleteView{
    // 把当前view添加到app的主window上去
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    
    // 添加按钮的动画
    [UIView animateWithDuration:1.f animations:^{
        self.deleteButton.frame = CGRectMake(self.bounds.size.width/2, self.bounds.size.height/2, 100, 100);
    }];
}

- (void)didmissDeleteView{
    // 移除当前view
    [self removeFromSuperview];
}

- (void)_deleteButtonClicked{
    
    // 在点击按钮的时候，执行_deleteBlock
    if (_deleteBlock) {
        _deleteBlock();
    }
    [self didmissDeleteView];
}

- (void)showDeleteViewWithPoint:(CGPoint)point clickBlock:(dispatch_block_t)clickBlock{
    
    // 先持有这个 block
    _deleteBlock = [clickBlock copy];;
    
    self.deleteButton.frame = CGRectMake(point.x, point.y, 100, 100);
    // 把当前view添加到app的主window上去
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    
    // 添加按钮的动画
    [UIView animateWithDuration:1.f animations:^{
        self.deleteButton.frame = CGRectMake(self.bounds.size.width/2, self.bounds.size.height/2, 100, 100);
    }];
}


@end
